// 定时时间提醒

var mongoose = require('mongoose');
var moment = require('moment');
var _ = require('underscore');
var CustomRemind = mongoose.model('CustomRemind');
var Schedule = mongoose.model('Schedule');
var scheduleDate = require('../util/scheduleDate');
var remoteRequest = require('../util/remoteRequest');
var config = require('../conf/config');
var period = config.constant.period;

module.exports = function() {

    var start  = function() {
        queryScheduled(function(reminds){
            _.each(reminds, function(remind){
                //消息发送
                sendRemindMsg(remind);
                // 时间更新或是数据删除
                remindUpdateOrDel(remind);
            });

            global.isLastComplete = true;
        });

        console.info('%s:消息提醒此轮结束!', moment().format('YYYY-MM-DD HH:mm:ss'));
    };

    var queryScheduled = function(callback) {
        // 查询出所有执行时间小于当前时间+ 1分钟的数据
        //CustomRemind.find({alarm : {$lte : moment(new Date()).add(1, 'minute').toDate()}}, function(err, reminds) {
        // 查询出所有执行时间小于或等于当前时间的数据
        CustomRemind.find({alarm : {$lte : new Date()}}, function(err, reminds) {
            if (err) {
                console.error('定时提醒数据扫描查询出错：%s', JSON.stringify(err));
                return;
            }

            !callback || callback(reminds);
        });
    };

    var sendRemindMsg = function(remind){
        Schedule.findById(remind.scheduleId, function(err, schedule){
            if (err) {
                console.error('根据日程id：%查询数据时出错：%s', remind.memberId, JSON.stringify(err));
                return;
            }

            //var titles = {
            //    TASK  : '您参加的任务' + remind.leadMinute + '分钟后结束',
            //    MEETING : '您参加的会议' + remind.leadMinute + '分钟后开始'
            //};

            var msgTime = {
                true    : moment(schedule.timeScope.start).format('YYYY-MM-DD HH:mm') + ' - ' + moment(schedule.timeScope.end).format('HH:mm'),
                false   : moment(schedule.timeScope.start).format('YYYY-MM-DD HH:mm') + ' 至 ' + moment(schedule.timeScope.end).format('YYYY-MM-DD HH:mm')
            };

            var msg = '日程管理动态推送通知<br>主题：' + schedule.subject + '<br>' + '时间：' + msgTime[moment(schedule.timeScope.start).isSame(schedule.timeScope.end, 'day')];
            var params = {
                users   :   [remind.memberId],
                msgBody :   [{
                    'description' : msg,
                    'picUrl': config.remote[config.currEvn].msgImgUrl,
                    'title': assemRemindText(schedule.isFullDay, remind.leadMinute, schedule.type),
                    'url': config.remote[config.currEvn].msgDetailUrl + schedule._id
                }]
            };

            console.info(remind.memberId);
            remoteRequest.sendMsg(params);
        });
    };

    var assemRemindText = function (isFullDay, remindMinute, scheduleType) {
        var result = '';
        var scheduleTypeText = scheduleType == config.constant.scheduleType.MEETING ? '会议' : '任务';
        var remindText = scheduleType == config.constant.scheduleType.MEETING ? '开始' : '结束';
        var oneDay = 60 * 24;
        if (!isFullDay && remindMinute == 0) {
            result = '您参加的' + scheduleTypeText + '已经' + remindText;
        } else if (!isFullDay && (remindMinute == 15 || remindMinute == 30)) {
            result = '您参加的' + scheduleTypeText + remindMinute + '分钟后' + remindText;
        } else if (!isFullDay && (remindMinute == 60 || remindMinute == 120)) {
            result = '您参加的' + scheduleTypeText + remindMinute/60 + '小时后' + remindText;
        } else if (!isFullDay && remindMinute == oneDay) {
            result = '您参加的' + scheduleTypeText + '1天后' + remindText;
        } else if (isFullDay && remindMinute == 0) {
            result = '您参加的' + scheduleTypeText + '今天' + remindText;
        } else if (isFullDay && (remindMinute == oneDay || remindMinute == oneDay * 2)) {
            result = '您参加的' + scheduleTypeText + remindMinute/oneDay + '天后' + remindText;
        } else {
            result = '您参加的' + scheduleTypeText + '即将' + remindText;
        }
        return result;
    };

    var remindUpdateOrDel = function(remind){
        // 如果是不重复提醒或是己到截止时间则删除
        if (remind.repeat == period.NONE || remind.deadline.getTime() < new Date().getTime()) {
            CustomRemind.remove({scheduleId: remind.scheduleId, memberId : remind.memberId}, function(err, num){
                if (err) {
                    console.error('删除提醒数据【%s】异常:%s', JSON.stringify(remind), JSON.stringify(err));
                }
            });

        // 更新下一时间
        } else {
            remind = scheduleDate.nextExecTime(remind);
            CustomRemind.update({scheduleId: remind.scheduleId, memberId : remind.memberId},
                {$set : {alarm : remind.alarm, lastModifyTime : new Date()}, $inc: { __v: 1 }},
                function(err, num){
                    if (err) {
                        console.error('修改提醒数据【%s】异常:%s', JSON.stringify(remind), JSON.stringify(err));
                    }
            });
        }
    };

    return {
        start   :   start
    };
}();